#pragma once

#include <iostream>
#include <memory>
#include "Epoller.hpp"
#include "Socket.hpp"
#include "log.hpp"

static const int defaultport = 8080;
static const int num = 64;

uint32_t EVENT_IN = EPOLLIN;
uint32_t EVENT_OUT = EPOLLOUT;

class EpollServer
{
public:
    EpollServer(uint16_t port = defaultport)
        : _listensock_ptr(new Sock),
          _epoller_ptr(new Epoller),
          _port(port)
    {
    }

    bool Init()
    {
        _listensock_ptr->Socket();
        _listensock_ptr->Bind(_port);
        _listensock_ptr->Listen();
        lg(Info, "Server Init.");
        return true;
    }

    void Start()
    {
        _epoller_ptr->EpollerUpdate(EPOLL_CTL_ADD, _listensock_ptr->Fd(), EVENT_IN);
        struct epoll_event revs[num];
        for (;;)
        {
            int n = _epoller_ptr->EpollerWait(revs, num);
            if (n > 0)
            {
                // 有事件就绪
                lg(Debug, "event happened, fd is: %d", revs[0].data.fd);
                Dispatcher(revs, n);
            }
            else if (n == 0)
            {
                // 触发timeout
                lg(Info, "time out...");
            }
            else
            {
                // epoll_wait 出错
                lg(Error, "epoll wait fail!");
            }
        }
    }

    ~EpollServer()
    {
        _listensock_ptr->Close();
    }

private:
    void Accepter()
    {
        std::string clientip;
        uint16_t clientport;
        int fd = _listensock_ptr->Accept(&clientip, &clientport);
        lg(Info, "accepter receive a link, clientip: %s , clientport: %d", clientip.c_str(), clientport);
        if (fd > 0)
        {
            _epoller_ptr->EpollerUpdate(EPOLL_CTL_ADD, fd, EVENT_IN);
        }
    }

    void Recver(int fd)
    {
        char buffer[1024];
        int n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "get a message: " << buffer << endl;

            std::string echo_str("server echo@ ");
            echo_str += buffer;
            write(fd, echo_str.c_str(), echo_str.size());
        }
        else if (n == 0)
        {
            lg(Info, "client close link, me too!");
            _epoller_ptr->EpollerUpdate(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
        else
        {
            lg(Warning, "read fail! the fd is: %d", fd);
            _epoller_ptr->EpollerUpdate(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
    }

    void Dispatcher(struct epoll_event *revs, int n)
    {
        for (int i = 0; i < n; ++i)
        {
            uint32_t event = revs[i].events;
            int fd = revs[i].data.fd;
            if (event & EVENT_IN)
            {
                if (fd == _listensock_ptr->Fd())
                {
                    Accepter();
                }
                else
                {
                    Recver(fd);
                }
            }
            else if(event & EVENT_OUT)
            {

            }
            else
            {

            }
        }
    }

private:
    std::shared_ptr<Sock> _listensock_ptr;
    std::shared_ptr<Epoller> _epoller_ptr;
    uint16_t _port;
};